package com.itlong.cloud.property.service.impl;

import com.alibaba.fastjson.JSON;
import com.itlong.cloud.POJO.PO.AmountChangeInfoPO;
import com.itlong.cloud.POJO.PO.PaymentTradePO;
import com.itlong.cloud.POJO.PO.PropertyPaymentBillPO;
import com.itlong.cloud.POJO.PO.PropertyPaymentDataRecordPO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.property.dao.IProjectAllowedCashWithdrawalStatisticsDao;
import com.itlong.cloud.property.service.IProjectAllowedCashWithdrawalStatisticsService;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <desc>
 *      物业-统计项目可提现余额服务接口实现类
 * </desc>
 *
 * @createDate 2018/9/26
 */
@Service
@RefreshScope
public class ProjectAllowedCashWithdrawalStatisticsServiceImpl implements IProjectAllowedCashWithdrawalStatisticsService {

    private static Logger LOG = LoggerFactory.getLogger(ProjectAllowedCashWithdrawalStatisticsServiceImpl.class);

    //商户号
    @Value("${" + PlatformConstants.MCHID + "}")
    public String MCHID;

    @Autowired
    private MessageSender messageSender;

    @Autowired
    private IProjectAllowedCashWithdrawalStatisticsDao iProjectAllowedCashWithdrawalStatisticsDao;

    /**
     * <desc>
     *      统计项目可提现余额，只统计前一天
     * </desc>
     *
     * @author wangzhi
     * @createDate 2018/09/26
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void statisticsAllowedCashWithdrawal() throws Exception {
        // 先查询出前一天产生的线上微信支付账单
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 1);
        String paramTime = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
        // 没有子账单的账单，如维修费等（目前查询的包含了停车费）
//        List<PropertyPaymentBillPO> propertyPaymentBillPOList = iProjectAllowedCashWithdrawalStatisticsDao.getBillOfStatisticsAllowedCashWithdrawal(paramTime);
        // 有子账单的账单，如抄表费物业费
//        List<PropertyPaymentDataRecordPO> propertyPaymentDataRecordPOList = iProjectAllowedCashWithdrawalStatisticsDao.getDataRecordOfStatisticsAllowedCashWithdrawal(paramTime);

        // 微信授权支付的逻辑改动，钱有直接流向物业商户号的场景，所以直接从订单表中去统计，以我司的商户号为条件过滤，避免钱到物业商户号了，可提现余额也加了
        List<PaymentTradePO> paymentTradePOList = iProjectAllowedCashWithdrawalStatisticsDao.getPaymentTradeOfStatisticsAllowedCashWithdrawal(paramTime, MCHID);

        // 资金变动明细中 交易类型 1物业抄表费  2维修费 3停车费 存在手续费，同时也可能存在物业增值费，要减去
        List<AmountChangeInfoPO> amountChangeInfoPOList = iProjectAllowedCashWithdrawalStatisticsDao.getAmountChangeInfoForStatisticsAllowedCashWithdrawal(paramTime);

        Map<String,BigDecimal> map = new HashMap<>();
        LOG.info("待统计订单paymentTradePOList：" + JSON.toJSONString(paymentTradePOList));
        for (PaymentTradePO paymentTradePO : paymentTradePOList){
            System.out.println(paymentTradePO);
            if (map.get(paymentTradePO.getProjectId()) == null || StringUtils.isBlank(map.get(paymentTradePO.getProjectId()).toString())) {
                map.put(paymentTradePO.getProjectId(),paymentTradePO.getPrice());
            } else {
                BigDecimal amount = map.get(paymentTradePO.getProjectId());
                map.put(paymentTradePO.getProjectId(),amount.add(paymentTradePO.getPrice()));
            }
        }
//        LOG.info("待统计子账单propertyPaymentDataRecordPOList：" + JSON.toJSONString(propertyPaymentDataRecordPOList));
//        for(PropertyPaymentDataRecordPO propertyPaymentDataRecordPO : propertyPaymentDataRecordPOList){
//            System.out.println(propertyPaymentDataRecordPO);
//            if (map.get(propertyPaymentDataRecordPO.getProjectId()) == null || StringUtils.isBlank(map.get(propertyPaymentDataRecordPO.getProjectId()).toString())) {
//                map.put(propertyPaymentDataRecordPO.getProjectId(),propertyPaymentDataRecordPO.getPaidAmount());
//            } else {
//                BigDecimal amount = map.get(propertyPaymentDataRecordPO.getProjectId());
//                map.put(propertyPaymentDataRecordPO.getProjectId(),amount.add(propertyPaymentDataRecordPO.getPaidAmount()));
//            }
//        }
        LOG.info("待统计资金变动明细数据amountChangeInfoPOList：" + JSON.toJSONString(amountChangeInfoPOList));
        for (AmountChangeInfoPO amountChangeInfoPO : amountChangeInfoPOList) {
            System.out.println(amountChangeInfoPO);
            BigDecimal amount = map.get(amountChangeInfoPO.getProjectId());
            if (amountChangeInfoPO.getTradeType() == 9) {
                // 物业增值费类型，则减去所扣物业增值费
                map.put(amountChangeInfoPO.getProjectId(),amount.subtract(amountChangeInfoPO.getTradeAmount()).subtract(amountChangeInfoPO.getHandlingFee()));
            } else {
                map.put(amountChangeInfoPO.getProjectId(),amount.subtract(amountChangeInfoPO.getHandlingFee()));
            }
        }
        // 发送消息队列到唯一改动金额的队列
        LOG.info("统计结果map：" + JSON.toJSONString(map));
        for (Map.Entry<String,BigDecimal> entry : map.entrySet()){
            System.out.println(entry);
            Map<String,Object> params=new HashMap<>();
            params.put("arithmeticFlag", "0"); // 运算: 0加,1减
            params.put("amount", entry.getValue().toString()); // 金额
            params.put("projectId", entry.getKey()); // 项目编号
            params.put("updateNameFlag","0"); // 0可提现余额,1实时余额   为空都更新
            messageSender.send(RabbitMQConstant.RABBITMQ_PROJECT_AMOUNT_MANAGER_QUEUE,
                    JSON.toJSONString(params),
                    RabbitMQConstant.RABBITMQ_PAY_EXCHANGE,
                    RabbitMQConstant.RABBITMQ_PROJECT_AMOUNT_ROUTING_KEY);
        }
    }

    /*public static void main(String[] args) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String day = "2018-10-01";
        Date date = simpleDateFormat.parse(day);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DATE,calendar.get(Calendar.DATE) - 1);
        System.out.println(simpleDateFormat.format(calendar.getTime()));
    }*/
}
